//
//  IndexLeftViewController.m
//  yigou
//
//  Created by SunChao on 17/3/6.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "IndexLeftViewController.h"

#import "DFBaseLineCell.h"
#import "ContentListCell.h"
#import "DFLineCommentItem.h"
#import "DFTextImageLineItem.h"
#import "DFLineCellManager.h"
#import "DFImagePreviewViewController.h"
#import "MMPopupItem.h"
#import "MMSheetView.h"
#import "MMPopupWindow.h"
#import "CommentInputView.h"
@interface IndexLeftViewController ()<UITableViewDataSource, UITableViewDelegate,DFLineCellDelegate,UINavigationControllerDelegate, DFImagePreviewViewControllerDelegate,CommentInputViewDelegate>


@property (nonatomic,strong)NSMutableArray *dataSource;

@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) BOOL pageToEnd;

@property (nonatomic, strong) NSMutableArray *items;

@property (nonatomic, strong) NSMutableDictionary *itemDic;

@property (nonatomic, strong) NSMutableDictionary *commentDic;

@property (strong, nonatomic) NSString * currentItemId;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@property (strong, nonatomic) NSMutableArray *topicHeights;
@property (strong, nonatomic) CommentInputView *commentInputView;

@property (strong, nonatomic) UIButton *totopButton;

@end

@implementation IndexLeftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageToEnd = NO;
    self.page = 1;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc]init];
   
    [self addRefreshHeader:self.tableView];
    [self addLoadMoreFooter:self.tableView];
    [[MMPopupWindow sharedWindow] cacheWindow];
    [MMPopupWindow sharedWindow].touchWildToHide = YES;
    MMSheetViewConfig *sheetConfig = [MMSheetViewConfig globalConfig];
    sheetConfig.defaultTextCancel = @"取消";
    _items = [NSMutableArray array];
    _itemDic = [NSMutableDictionary dictionary];
    _commentDic = [NSMutableDictionary dictionary];
    [self initCommentInputView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(IndexNewVCTabButtonClicked) name:@"IndexNewVCTabButtonClicked" object:nil];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapTableView)];
//    [self.tableView addGestureRecognizer:tap];
    
    self.totopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.totopButton.frame = CGRectMake(ScreenWidth - 65, ScreenHeight - 200, 50, 50);
    [self.totopButton setImage:[UIImage imageNamed:@"backtotop"] forState:UIControlStateNormal];
    self.totopButton.hidden = YES;
    [self.totopButton addTarget:self action:@selector(totopClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.totopButton];
    [self loadLocalData];
}

- (void)totopClicked:(UIButton *)button {
    [self.tableView setContentOffset:CGPointZero animated:YES];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"IndexNewVCTabButtonClicked" object:nil];
}
- (void)IndexNewVCTabButtonClicked{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"HiddenCommentBar" object:nil];
    [_commentInputView hideInputView];
}
//- (void)TapTableView{
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"HiddenCommentBar" object:nil];
//}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [ViewFactory setNavigationBlack:self];
    
    [_commentInputView addNotify];
    [_commentInputView addObserver];
    [self loadNetworkData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [_commentInputView removeNotify];
    
    [_commentInputView removeObserver];
    
}

-(void) initCommentInputView
{
    if (_commentInputView == nil) {
        _commentInputView = [[CommentInputView alloc] initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _commentInputView.hidden = YES;
        _commentInputView.delegate = self;
        [self.view addSubview:_commentInputView];
    }
    
}
- (void)calculateHeight {
    [self.topicHeights removeAllObjects];
    for(NSInteger i = 0; i < _items.count; i++) {
        DFBaseLineItem *item = [_items objectAtIndex:i];
        DFBaseLineCell *typeCell = [self getCell:[item class]];
        NSInteger height = [typeCell getReuseableCellHeight:item]+40;
        [self.topicHeights addObject:[NSNumber numberWithInteger:height]];
    }
}

#pragma mark TableViewDelegate &  DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _items.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *numh = self.topicHeights[indexPath.row];
    return [numh integerValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
    NSLog(@"----------indexpath:%ld",indexPath.row);
    DFBaseLineCell *typeCell = [self getCell:[item class]];
    
    NSString *reuseIdentifier = NSStringFromClass([typeCell class]);
    DFBaseLineCell *cell = [tableView dequeueReusableCellWithIdentifier: reuseIdentifier];
    if (cell == nil ) {
        cell = [[[typeCell class] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }else{
        NSLog(@"重用Cell: %@", reuseIdentifier);
    }
    
    cell.delegate = self;
    
    cell.separatorInset = UIEdgeInsetsZero;
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        cell.layoutMargins = UIEdgeInsetsZero;
    }
    [cell updateWithItem:item];
    
    return cell;
    
}

#pragma -mark 数据请求

- (void)refresh {
    [super refresh];
    [self.dataSource removeAllObjects];
    [self loadNetworkData];
    
}


- (void)loadLocalData {
    NSDictionary *data = [[TMCache sharedCache] objectForKey:@"IndexLeftData"];
    if (data) {
        NSArray *dataArr = [data objectForKey:@"data"];
        if (dataArr) {
            [_items removeAllObjects];
            [self initDataWithArray:dataArr];
            [self calculateHeight];
            __weak __typeof(self) weakself= self;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakself.tableView reloadData];
                [weakself.tableView.header endRefreshing];
                
            });
        }
    }
}

- (void)loadNetworkData{
    self.page = 1;
    DYBaseRequest *request = [DYBaseRequest new];
    //NSString *url = [NSString stringWithFormat:@"%@/sys/index/init", APIYIGOU];
    NSString *url = [NSString stringWithFormat:@"%@/sys/index/hotTopic", APIYIGOU];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [[TMCache sharedCache] setObjectWithTimeStamp:dict forKey:@"IndexLeftData" block:nil];
        NSArray *dataArr = [dict objectForKey:@"data"];
        [_items removeAllObjects];
        [self initDataWithArray:dataArr];
        [self calculateHeight];
        if (dataArr.count == 0) {
            [ViewFactory showSuccess:@"没有数据！"];
        }
        
        __weak __typeof(self) weakself= self;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakself.tableView reloadData];
            [weakself.tableView.header endRefreshing];
            
        });
        
        
    } error:^(YTKBaseRequest *request) {
        [self.tableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.header endRefreshing];
        
    }];
}


- (void)loadMore {
    [super loadMore];
    DYBaseRequest *request = [DYBaseRequest new];
    self.page +=1;
   
    NSString *url = [NSString stringWithFormat:@"%@/sys/index/hotTopic?page=%ld", APIYIGOU, (long)self.page];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSArray *dataArr = [dict objectForKey:@"data"];
        if (dataArr.count == 0) {
            [ViewFactory showSuccess:@"没有更多数据了！"];
            [self.tableView.footer endRefreshing];
            return ;
        }
            NSArray *addTopicListArr = dataArr;
            [self initDataWithArray:addTopicListArr];
            [self calculateHeight];
        
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
        
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}




//初始化文章数据
-(void) initDataWithArray:(NSArray *)array
{
    
    NSArray *topicArr = array;
    for (NSDictionary *tmpDic in topicArr) {
        NSDictionary *topicDic = [tmpDic objectForKey:@"topic"];
        NSLog(@"dic:%@",topicDic);
        DFTextImageLineItem *textImageItem = [[DFTextImageLineItem alloc] init];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.user_id = [topicDic objectForKey:@"user_id"];
        textImageItem.head_url = [[topicDic objectForKey:@"hyUser"] objectForKey:@"head_url"];
        textImageItem.nick_name = [[topicDic objectForKey:@"hyUser"] objectForKey:@"nick_name"];
        textImageItem.title = [topicDic objectForKey:@"title"];
        textImageItem.text = [topicDic objectForKey:@"content_desc"];
        textImageItem.tribe_name = [topicDic objectForKey:@"tribe_name"];
        textImageItem.publish_tm = [topicDic objectForKey:@"publish_tm"];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.tribe_id = [topicDic objectForKey:@"tribe_id"];
        textImageItem.shareUrl = [topicDic objectForKey:@"shareUrl"];
        textImageItem.cover_img = [topicDic objectForKey:@"cover_img"];
        NSArray *picArr = [topicDic objectForKey:@"mediaList"];
        NSMutableArray *srcImages = [NSMutableArray array];
        for (NSDictionary *tmpDic in picArr) {
            NSString *imgString =  [tmpDic objectForKey:@"media_url"];
            [srcImages addObject:imgString];
        }
        [textImageItem.srcImages removeAllObjects];
        
        textImageItem.srcImages = srcImages;
        
        NSArray *contentCmt = [tmpDic objectForKey:@"contentCmtList"];
        
        for (NSDictionary *cmtDic in contentCmt) {
            NSLog(@"cmtArr:%@",cmtDic);
            DFLineCommentItem *commentItem1_1 = [[DFLineCommentItem alloc] init];
            commentItem1_1.commentId = [cmtDic objectForKey:@"comment_id"];
            commentItem1_1.userId = [cmtDic objectForKey:@"user_id"];
            commentItem1_1.userNick = [cmtDic objectForKey:@"user_nike_name"];
            if (![[cmtDic objectForKey:@"reply_user_id"]isEqualToString:@""]) {
                commentItem1_1.replyUserId = [cmtDic objectForKey:@"reply_user_id"];
                commentItem1_1.replyUserNick = [cmtDic objectForKey:@"reply_user_nike_name"];
            }
            
            commentItem1_1.text = [cmtDic objectForKey:@"comment"];
            
            [textImageItem.comments addObject:commentItem1_1];
        }
        
        NSArray *contentLike = [tmpDic objectForKey:@"contentLikeList"];
        [textImageItem.likes removeAllObjects];
        for (NSDictionary *tmpDic in contentLike) {
            DFLineLikeItem *likeItem1_1 = [[DFLineLikeItem alloc] init];
            likeItem1_1.userId = [tmpDic objectForKey:@"user_id"];
            likeItem1_1.userNick = [tmpDic objectForKey:@"nick_name"];
            likeItem1_1.head_url = [tmpDic objectForKey:@"head_url"];
            [textImageItem.likes addObject:likeItem1_1];
        }
        [self addItem:textImageItem];
    }
    
}

#pragma mark - Method

-(DFBaseLineCell *) getCell:(Class)itemClass
{
    DFLineCellManager *manager = [DFLineCellManager sharedInstance];
    return [manager getCell:itemClass];
}

-(void)addItem:(DFBaseLineItem *)item
{
    [self insertItem:item index:_items.count];
}

-(void) addItemTop:(DFBaseLineItem *) item
{
    [self insertItem:item index:0];
}

-(void) insertItem:(DFBaseLineItem *) item index:(NSUInteger)index
{
    [self genCommentAttrString:item];
    
    [_items insertObject:item atIndex:index];
    
    
    [_itemDic setObject:item forKey:item.content_id];
}

-(DFBaseLineItem *) getItem:(NSString *) itemId
{
    return [_itemDic objectForKey:itemId];
    
}

-(void)addCommentItem:(DFLineCommentItem *)commentItem itemId:(NSString *)itemId replyCommentId:(NSString *)replyCommentId

{
    NSString *contentId = itemId;
    NSString *text = commentItem.text;
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
        DFBaseLineItem *item = [self getItem:itemId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        [tmpArr addObject:commentItem];
        [tmpArr addObjectsFromArray:item.comments];
        [item.comments removeAllObjects];
        item.comments = tmpArr;
        
        if (![replyCommentId isEqualToString:@"0"]) {
            DFLineCommentItem *replyCommentItem = [self getCommentItem:replyCommentId];
            
            commentItem.replyUserId = replyCommentItem.userId;
            commentItem.replyUserNick = replyCommentItem.userNick;
            
        }
        
        item.cellHeight = 0;
        [self genCommentAttrString:item];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:@"评论失败！"];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];

//    [self AddCommentDataRequestWithReplyCommentId:replyCommentId ContentId:itemId CommentText:commentItem.text];
    
    
    
}
- (void)AddCommentDataRequestWithReplyCommentId:(NSString *)replyCommentId ContentId:(NSString *)contentId CommentText:(NSString *)text{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
    
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:@"评论失败！"];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}
-(void) genCommentAttrString:(DFBaseLineItem *)item
{
    NSMutableArray *comments = item.comments;
    
    [item.commentStrArray removeAllObjects];
    
    for (int i=0; i<comments.count;i++) {
        DFLineCommentItem *comment = [comments objectAtIndex:i];
        [_commentDic setObject:comment forKey:comment.commentId];
        
        NSString *resultStr;
        if (comment.replyUserId == 0) {
            resultStr = [NSString stringWithFormat:@"%@: %@",comment.userNick, comment.text];
        }else{
            resultStr = [NSString stringWithFormat:@"%@回复%@: %@",comment.userNick, comment.replyUserNick, comment.text];
        }
        
        NSMutableAttributedString *commentStr = [[NSMutableAttributedString alloc]initWithString:resultStr];
        if (comment.replyUserId == 0) {
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(0, comment.userNick.length)];
        }else{
            NSUInteger localPos = 0;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(localPos, comment.userNick.length)];
            localPos += comment.userNick.length + 2;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.replyUserId] range:NSMakeRange(localPos, comment.replyUserNick.length)];
        }
        
        NSLog(@"ffff: %@", resultStr);
        
        [item.commentStrArray addObject:commentStr];
    }
     [self calculateHeight];
}
-(void)onLike:(NSString *)contentId likeItem:(DFLineLikeItem *)likeItem type:(BOOL)type
{
    //点赞
    if (type) {
        
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        [tmpArr addObjectsFromArray:item.likes];
        [item.likes removeAllObjects];
        item.likes = tmpArr;
    }else {
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i<item.likes.count; i++) {
            DFLineLikeItem *tmpItem =  [item.likes objectAtIndex:i];
            if ([tmpItem.userId isEqualToString:likeItem.userId]) {
                //                NSLog(@"有一样的");
                [array addObject:tmpItem];
            }
        }
        [item.likes removeObjectsInArray:array];
    }
    
    [self.tableView reloadData];
}

-(DFLineCommentItem *)getCommentItem:(NSString *)commentId
{
    return [_commentDic objectForKey:commentId];
}



-(void)onComment:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.commentId = @"0";
    
    _commentInputView.hidden = NO;
    
    [_commentInputView show];
}

-(void)onClickComment:(NSString *)commentId itemId:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.hidden = NO;
    
    _commentInputView.commentId = commentId;
    
    [_commentInputView show];
    
    DFLineCommentItem *comment = [_commentDic objectForKey:commentId];
    [_commentInputView setPlaceHolder:[NSString stringWithFormat:@"  回复: %@", comment.userNick]];
}

-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text {
    DFLineCommentItem *commentItem = [[DFLineCommentItem alloc] init];
    commentItem.commentId = commentId;
    commentItem.userId = [UserData userid];
    commentItem.userNick = [UserData username];
    commentItem.text = text;
    [self addCommentItem:commentItem itemId:_currentItemId replyCommentId:commentId];
}
#pragma mark - UIViewControllerPreviewingDelegate

//-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
//{
//    NSIndexPath *indexPath=[self.tableView indexPathForRowAtPoint:location];
//    
//    if(indexPath)
//    {
//        
//        DFBaseLineCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//        
//        if (cell && [cell isKindOfClass:[DFTextImageLineCell class]]) {
//            DFTextImageLineCell *imageCell = (DFTextImageLineCell *)cell;
//            //            NSInteger index = [imageCell getIndexFromPoint:location];
//            
//            DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
//            if (item && [item isKindOfClass:[DFTextImageLineItem class]]) {
//                DFTextImageLineItem *textItem = (DFTextImageLineItem *) item;
//                if (index == -1) {
//                    return nil;
//                }
//                NSString *url  = [textItem.srcImages objectAtIndex:index];
//                DFImagePreviewViewController *previewController=[[DFImagePreviewViewController alloc] initWithImageUrl:url itemId:item.content_id];
//                previewController.delegate = self;
//                previewController.preferredContentSize=CGSizeMake(300, 300);
//                return previewController;
//            }
//        }
//    }
//    return nil;
//}
//-(void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
//{
//    [self showViewController:viewControllerToCommit sender:self];
//}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    if (offset.y > ScreenHeight ) {
        self.totopButton.hidden = NO;
    } else {
        self.totopButton.hidden = YES;
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"HiddenCommentBar" object:nil];
}

ARRAY_INIT(topicHeights)
@end
